package com.neu.handler;

import com.neu.base.AuthContants;
import com.neu.base.Result;
import com.neu.utils.JwtUtils;
import com.neu.utils.RedisUtil;
import com.neu.utils.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
@Slf4j
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {
    private RedisUtil redisUtils;
    private JwtUtils jwtUtils;

    public LogoutSuccessHandlerImpl(RedisUtil redisUtils, JwtUtils jwtUtils) {
        this.redisUtils = redisUtils;
        this.jwtUtils = jwtUtils;

    }

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String token = request.getHeader("Authorization");
        if (token != null) {
            if (jwtUtils.isTokenExpired(token)) {
                log.warn("Access Token 已过期");
                // 返回提示客户端重新登录
                ServletUtils.renderResult(response, Result.success("Access Token 已过期，请重新登录"));
                return;
            }
            String username = jwtUtils.getClaims(token).getSubject();
            redisUtils.delete(AuthContants.REDIS_KEY_AUTH_TOKEN + username);
            redisUtils.delete(AuthContants.REDIS_KEY_AUTH_USER_DETAIL + username);
        }
        // 清空响应头中的token 防止前端继续携带token
        response.setHeader("Authorization", "");
        ServletUtils.renderResult(response, Result.success("退出成功"));
        log.info("用户退出登录");
    }
}
